<script setup>
import { Head, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import StatCard from '@/Components/UI/StatCard.vue'
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { 
    DocumentTextIcon, 
    UserGroupIcon, 
    ChatBubbleLeftEllipsisIcon,
    TagIcon,
    FolderIcon,
    EyeIcon,
    HeartIcon,
    ChartBarIcon,
    ArrowTrendingUpIcon,
    ArrowTrendingDownIcon,
    FireIcon
} from '@heroicons/vue/24/outline'
import { usePage } from '@inertiajs/vue3'

const page = usePage()
const user = computed(() => page.props.auth.user)

const props = defineProps({
    stats: {
        type: Object,
        required: true
    },
    trend: {
        type: Array,
        required: true
    },
    categoryStats: {
        type: Array,
        required: true
    },
    recentPosts: {
        type: Array,
        required: true
    },
    popularPosts: {
        type: Array,
        required: true
    },
    activeUsers: {
        type: Array,
        required: true
    }
})

// 计算趋势变化
const calculateTrend = (current, previous) => {
    if (!previous || previous === 0) return null
    const change = ((current - previous) / previous) * 100
    return {
        value: Math.abs(change).toFixed(1),
        isUp: change > 0
    }
}

// 计算趋势数据
const trends = computed(() => {
    const trendData = props.trend || []
    const previousCount = trendData.length > 1 ? trendData[trendData.length - 2]?.count || 0 : 0
    const currentCount = trendData.length > 0 ? trendData[trendData.length - 1]?.count || 0 : 0
    
    return {
        posts: calculateTrend(props.stats.total_posts, props.stats.total_posts - currentCount),
        views: calculateTrend(props.stats.total_views || 0, (props.stats.total_views || 0) - (currentCount * 10))
    }
})

// 图表相关
let chart = null

onMounted(() => {
    // 动态加载 Chart.js
    if (typeof window !== 'undefined' && !window.Chart) {
        const script = document.createElement('script')
        script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js'
        script.onload = initChart
        document.head.appendChild(script)
    } else {
        initChart()
    }
})

const initChart = () => {
    const ctx = document.getElementById('trendsChart')
    if (window.Chart && ctx) {
        chart = new window.Chart(ctx, {
            type: 'line',
            data: {
                labels: props.trend.map(t => t.date).reverse(),
                datasets: [{
                    label: '文章数',
                    data: props.trend.map(t => t.count).reverse(),
                    borderColor: '#f97316',
                    backgroundColor: 'rgba(249, 115, 22, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#f97316',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        padding: 12,
                        titleFont: {
                            size: 14
                        },
                        bodyFont: {
                            size: 13
                        },
                        cornerRadius: 8
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1,
                            font: {
                                size: 12
                            }
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        ticks: {
                            font: {
                                size: 12
                            }
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        })
    }
}

onBeforeUnmount(() => {
    if (chart) {
        chart.destroy()
    }
})
</script>

<template>
    <AdminLayout>
        <Head title="仪表盘" />

        <div class="space-y-8">
            <!-- 页面标题 -->
            <div>
                <h1 class="text-3xl font-bold text-gray-900">
                    仪表盘
                </h1>
                <p class="mt-2 text-sm text-gray-600">
                    欢迎回来，{{ user?.name || '管理员' }}！这里是您的博客数据概览
                </p>
            </div>

            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
                <StatCard 
                    title="文章总数" 
                    :value="stats.total_posts" 
                    :icon="DocumentTextIcon"
                    icon-color="text-blue-600"
                    icon-bg-color="bg-blue-50"
                    :trend="trends.posts"
                />
                
                <StatCard 
                    title="已发布" 
                    :value="stats.published_posts" 
                    :icon="DocumentTextIcon"
                    icon-color="text-green-600"
                    icon-bg-color="bg-green-50"
                />
                
                <StatCard 
                    title="草稿" 
                    :value="stats.draft_posts" 
                    :icon="DocumentTextIcon"
                    icon-color="text-yellow-600"
                    icon-bg-color="bg-yellow-50"
                />
                
                <StatCard 
                    title="用户数" 
                    :value="stats.total_users" 
                    :icon="UserGroupIcon"
                    icon-color="text-purple-600"
                    icon-bg-color="bg-purple-50"
                />
                
                <StatCard 
                    title="评论数" 
                    :value="stats.total_comments" 
                    :icon="ChatBubbleLeftEllipsisIcon"
                    icon-color="text-pink-600"
                    icon-bg-color="bg-pink-50"
                />
                
                <StatCard 
                    title="分类数" 
                    :value="stats.total_categories" 
                    :icon="FolderIcon"
                    icon-color="text-orange-600"
                    icon-bg-color="bg-orange-50"
                />
                
                <StatCard 
                    title="标签数" 
                    :value="stats.total_tags" 
                    :icon="TagIcon"
                    icon-color="text-indigo-600"
                    icon-bg-color="bg-indigo-50"
                />
                
                <StatCard 
                    title="总浏览量" 
                    :value="stats.total_views || 0" 
                    :icon="EyeIcon"
                    icon-color="text-cyan-600"
                    icon-bg-color="bg-cyan-50"
                    :trend="trends.views"
                />
            </div>

            <!-- 图表和分类统计 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- 发布趋势图表 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <ChartBarIcon class="h-5 w-5 text-gray-400 mr-2" />
                                <h3 class="text-lg font-semibold text-gray-900">
                                    最近30天发布趋势
                                </h3>
                            </div>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="h-64">
                            <canvas id="trendsChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- 分类统计 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center">
                            <FolderIcon class="h-5 w-5 text-gray-400 mr-2" />
                            <h3 class="text-lg font-semibold text-gray-900">
                                文章分类统计
                            </h3>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div
                                v-for="category in categoryStats"
                                :key="category.name"
                                class="flex items-center gap-4"
                            >
                                <span class="flex-1 text-sm font-medium text-gray-900 min-w-0 truncate">
                                    {{ category.name }}
                                </span>
                                <div class="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden max-w-xs">
                                    <div
                                        class="h-full bg-orange-500 rounded-full transition-all"
                                        :style="{ width: `${categoryStats.length > 0 ? (category.count / Math.max(...categoryStats.map(c => c.count))) * 100 : 0}%` }"
                                    ></div>
                                </div>
                                <span class="text-sm font-semibold text-gray-900 w-12 text-right">
                                    {{ category.count }}
                                </span>
                            </div>
                            <div v-if="categoryStats.length === 0" class="text-center py-8 text-gray-500 text-sm">
                                暂无分类数据
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 最近文章和热门文章 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- 最近文章 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <DocumentTextIcon class="h-5 w-5 text-gray-400 mr-2" />
                                <h3 class="text-lg font-semibold text-gray-900">
                                    最近文章
                                </h3>
                            </div>
                            <Link
                                :href="route('admin.posts.index')"
                                class="text-sm text-orange-600 hover:text-orange-700 font-medium"
                            >
                                查看全部
                            </Link>
                        </div>
                    </div>
                    <div class="divide-y divide-gray-200">
                        <div
                            v-for="post in recentPosts"
                            :key="post.id"
                            class="p-4 hover:bg-gray-50 transition-colors"
                        >
                            <div class="flex items-start justify-between">
                                <div class="flex-1 min-w-0">
                                    <Link
                                        :href="route('admin.posts.show', post.id)"
                                        class="block text-sm font-medium text-gray-900 hover:text-orange-600 truncate"
                                    >
                                        {{ post.title }}
                                    </Link>
                                    <div class="mt-1 flex items-center gap-2 text-xs text-gray-500">
                                        <span>{{ post.author }}</span>
                                        <span>·</span>
                                        <span>{{ post.category || '未分类' }}</span>
                                        <span>·</span>
                                        <span>{{ post.published_at || '未发布' }}</span>
                                    </div>
                                </div>
                                <span
                                    :class="[
                                        'ml-3 flex-shrink-0 inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
                                        post.status === 'published' 
                                            ? 'bg-green-100 text-green-800'
                                            : 'bg-yellow-100 text-yellow-800'
                                    ]"
                                >
                                    {{ post.status === 'published' ? '已发布' : '草稿' }}
                                </span>
                            </div>
                        </div>
                        <div v-if="recentPosts.length === 0" class="p-8 text-center text-gray-500 text-sm">
                            暂无文章
                        </div>
                    </div>
                </div>

                <!-- 热门文章 -->
                <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div class="p-6 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <FireIcon class="h-5 w-5 text-gray-400 mr-2" />
                                <h3 class="text-lg font-semibold text-gray-900">
                                    热门文章
                                </h3>
                            </div>
                            <Link
                                :href="route('admin.posts.index')"
                                class="text-sm text-orange-600 hover:text-orange-700 font-medium"
                            >
                                查看全部
                            </Link>
                        </div>
                    </div>
                    <div class="divide-y divide-gray-200">
                        <div
                            v-for="(post, index) in popularPosts"
                            :key="post.id"
                            class="p-4 hover:bg-gray-50 transition-colors"
                        >
                            <div class="flex items-start gap-3">
                                <div
                                    :class="[
                                        'flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-full text-sm font-semibold',
                                        index === 0
                                            ? 'bg-orange-100 text-orange-800'
                                            : 'bg-gray-100 text-gray-600'
                                    ]"
                                >
                                    {{ index + 1 }}
                                </div>
                                <div class="flex-1 min-w-0">
                                    <Link
                                        :href="route('admin.posts.show', post.id)"
                                        class="block text-sm font-medium text-gray-900 hover:text-orange-600 truncate"
                                    >
                                        {{ post.title }}
                                    </Link>
                                    <div class="mt-1 flex items-center gap-3 text-xs text-gray-500">
                                        <span class="flex items-center gap-1">
                                            <EyeIcon class="h-4 w-4" />
                                            {{ post.views || 0 }}
                                        </span>
                                        <span class="flex items-center gap-1">
                                            <HeartIcon class="h-4 w-4" />
                                            {{ post.likes || 0 }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-if="popularPosts.length === 0" class="p-8 text-center text-gray-500 text-sm">
                            暂无热门文章
                        </div>
                    </div>
                </div>
            </div>

            <!-- 活跃用户 -->
            <div class="bg-white rounded-lg border border-gray-200 shadow-sm">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <UserGroupIcon class="h-5 w-5 text-gray-400 mr-2" />
                            <h3 class="text-lg font-semibold text-gray-900">
                                活跃用户
                            </h3>
                        </div>
                        <Link
                            :href="route('admin.users.index')"
                            class="text-sm text-orange-600 hover:text-orange-700 font-medium"
                        >
                            查看全部
                        </Link>
                    </div>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
                        <div
                            v-for="user in activeUsers"
                            :key="user.name"
                            class="flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors"
                        >
                            <img
                                v-if="user.avatar"
                                :src="user.avatar"
                                :alt="user.name"
                                class="h-10 w-10 rounded-full"
                            >
                            <div
                                v-else
                                class="h-10 w-10 rounded-full bg-orange-100 flex items-center justify-center"
                            >
                                <span class="text-sm font-medium text-orange-600">
                                    {{ user.name?.charAt(0) || 'U' }}
                                </span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-gray-900 truncate">
                                    {{ user.name }}
                                </p>
                                <div class="flex items-center gap-2 text-xs text-gray-500 mt-0.5">
                                    <span>{{ user.posts_count || 0 }} 文章</span>
                                    <span>·</span>
                                    <span>{{ user.comments_count || 0 }} 评论</span>
                                </div>
                            </div>
                        </div>
                        <div v-if="activeUsers.length === 0" class="col-span-full text-center py-8 text-gray-500 text-sm">
                            暂无活跃用户
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
